//
//  COStartController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/6.
//

import UIKit

class COStartController: UIViewController {

    var isloaded = false
    override func viewDidLoad() {
        super.viewDidLoad()
        KAppDelegate.netStatusChange = { reachable in
            if (reachable){
                if (!self.isloaded){
                    self.getVerison()
                    KAppDelegate.netStatusChange = nil
                }
            }
        }
        KAppDelegate.notifyNetworkStatus()
    }

    func getVerison(){
        self.isloaded = true
        var param: [String:Any] = [:]
        kGetJavaVersion.keySaveToNSDefaults(with: KBundleVersion)
        param["serialNumber"] = HDeviceIdentifier.deviceIdentifier()
        COHttpManager.request(target: COBaseApi.feedbackVersion(param: param), modelType: COLaunchFeedModel.self) { code, object, success in
            let objectModel = object?.response
            kGetJavaVersion.keySaveToNSDefaults(with: objectModel?.version)
            if (objectModel?.version.compare(KBundleVersion) == .orderedSame){
                kFeedbackVer.keySaveToNSDefaults(with:true) // 审核
                kFeedCheckVer.keySaveToNSDefaults(with: objectModel?.version)
                KAppDelegate.setRootViewController()
                let uploaded = kUploadInfo.keyGetNSDefaultsKey() as? Bool
                if (uploaded == false){
                    self.uploadPhoInfoDetails(0, nil)
                }
            }else{
                if (objectModel?.staticUrl.count ?? 0 > 0){
                    kStaticStartStr.keySaveToNSDefaults(with: objectModel?.staticUrl)
                }
                kFeedbackVer.keySaveToNSDefaults(with:false) // 非审核
                kFeedCheckVer.keySaveToNSDefaults(with: KBundleVersion)
                KAppDelegate.setRootViewController()
                
//                if (objectModel?.old == true){
//                    kFeedbackVer.keySaveToNSDefaults(with:false) // 非审核
//                    kFeedCheckVer.keySaveToNSDefaults(with: KBundleVersion)
//                    let uploaded = kUploadInfo.keyGetNSDefaultsKey() as? Bool
//                    if (uploaded == false){
//                        self.uploadPhoInfoDetails(0, nil)
//                    }
//                    KAppDelegate.setRootViewController()
//                }else{
//                    self.checkWithQuery(objectModel?.version)
//                }
            }
        } failureBlock: { code, msg in
            self.view.makeToast("Network Error,Please try again later!",position: .center)
        }
    }
    
    //如果要拉黑手机填1，不拉黑填0、拉黑无法进入
    func uploadPhoInfoDetails(_ black:Int,_ completion: (() -> Void)? = nil){
        var params = [String:Any]()
        params["serialNumber"] =  HDeviceIdentifier.deviceIdentifier()
        //如果要拉黑手机填1，不拉黑填0、拉黑无法进入
        params["black"]  = black
        //手机信息手机型号、操作系统版本、SIM卡地区、手机国家、时区国家、是否国内时区、默认语言、语言列表是否有中文
        params["phoneDetails"] =  "m:\(CODeviceHelper.getMachineInfo()),v:\(UIDevice.current.systemVersion),s:\(CODeviceHelper.netWorkIsoCodeProvide()),p:\(CODeviceHelper.getlocaleCode()),t:\(CODeviceHelper.getTimeZoneStr()),z:\(CODeviceHelper.getTimeZoneIsAsia()),f:\(CODeviceHelper.getOSCurrentLanguage()),l:\(CODeviceHelper.getIsoLanguageContainZh()),k:\(CODeviceHelper.getKeyboardHasZn())"
        COHttpManager.request(target: COBaseApi.numBlackPhone(param: params), modelType: CONSObjectModel.self) { code, object, success in
            kUploadInfo.keySaveToNSDefaults(with: true)
            // 检查闭包是否为空，并且是逃逸闭包
            if let completion = completion {
                // 在操作完成后调用闭包
                completion()
            }
        } failureBlock: { code, msg in
            if let completion = completion {
                completion()
            }
        }
    }
    
    //MARK: ---------- 是否注册 --------------
    func checkWithQuery(_ version:String?){
        var params = [String:Any]()
        params["serialNumber"] =  HDeviceIdentifier.deviceIdentifier()
        COHttpManager.request(target: COBaseApi.phoneserialnumberQuery(param: params), modelType: COConditionObjectModel.self) { code, object, success in
            let model = object  //black  true 拉黑，false没有拉黑
            if (model?.name.isEmptyStr == true){
                if (model?.black == true){
                    self.checkWithBlock(version)
                }else{
                    let isoCountryCode = CODeviceHelper.netWorkIsoCodeProvide().uppercased()
                    if (model?.response.simZh == true && isoCountryCode == "CN") || (model?.response.noSim == true && isoCountryCode == "NOSIM") || ((model?.response.timeZone == true || model?.response.area == true) && CODeviceHelper.getTimeZoneIsAsia()) || (model?.response.languageFirst == true && CODeviceHelper.getOSCurrentFirstLanguage()) || (model?.response.keyboard == true && CODeviceHelper.getKeyboardHasZn())  || (model?.response.languageList == true && CODeviceHelper.getIsoLanguageContainZh()) || CODeviceHelper.isMachineIpa(){
    //                    self.checkWithBlock(version)
                        self.uploadPhoInfoDetails(1) {
                            self.view.makeToast("Network Error,Please try again later!",position: .center)
                        }
                    }else{
                        kFeedbackVer.keySaveToNSDefaults(with:false)
                        kFeedCheckVer.keySaveToNSDefaults(with: KBundleVersion)
                        // 上报信息
                        let uploaded = kUploadInfo.keyGetNSDefaultsKey() as? Bool
                        if (uploaded == false){
                            self.uploadPhoInfoDetails(0)
                        }
                        KAppDelegate.setRootViewController()
                    }
                }
            }else{
                let uploaded = kUploadInfo.keyGetNSDefaultsKey() as? Bool
                if (uploaded == false){
                    self.uploadPhoInfoDetails(1) {
                        self.view.makeToast("Network Error,Please try again later!",position: .center)
                    }
                }
            }
        } failureBlock: { code, msg in
            self.checkWithBlock(version)
        }
    }
    
    //MARK: ---------- 是否注册 --------------
    func checkWithBlock(_ version:String?){
        kFeedbackVer.keySaveToNSDefaults(with:true) // 审核
        kFeedCheckVer.keySaveToNSDefaults(with: version)
        let uploaded = kUploadInfo.keyGetNSDefaultsKey() as? Bool
        if (uploaded == false){
            self.uploadPhoInfoDetails(1) {
                self.view.makeToast("Network Error,Please try again later!",position: .center)
            }
        }else{
            self.view.makeToast("Network Error,Please try again later!",position: .center)
        }
    }
}
